package watch.app;

import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.SlidingDrawer.OnDrawerScrollListener;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;

public class watchActivity extends Activity {
	
	private int DST = 0;
	
	//Offset from phone locale, to adjust time
	private int offHours;
	private int offMin;
	
	//Offset for Date
	private int offDay;
	private int offMonth;
	private int offYear;
	
	//For stopwatch
	private int wHours;
	private int wMin;
	private int wSec;
	
	//For setting alarm
	private int mHour;
	private int mMinute;
	
	//For setting timezone
	private int selTimezone;
	
	//12 or 24 hr time
	Boolean amPm = false;
	//Stopwatch running
	Boolean counting = false;
	
	//Dialog for setting alarm
	static final int ALARM_DIALOG_ID = 0;
	//Dialog for setting time
	static final int TIME_DIALOG_ID = 1;
	//Dialog for settings Date
	static final int DATE_DIALOG_ID = 2;
	//Dialog for setting time
	static final int TIMEZONE_DIALOG_ID = 3;
	
	Boolean alarmSet = false;
	Boolean timeSet = false;
	Boolean dateSet = false;
	boolean timezoneSet = false;
    boolean alarm = false;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) { 
	    super.onCreate(savedInstanceState); 
	    
	    setContentView(R.layout.main);
	    
	    //((TextView)findViewById(R.id.alarmText)).setText("OFF"); // so it doesn't say alarm by default
	    ImageButton alarmStatus = (ImageButton) findViewById(R.id.bellSmall);
	    alarmStatus.setVisibility(View.GONE);
	    
	    /* Alarm stuff */
	    ImageButton alarms = (ImageButton) findViewById(R.id.alarms);
	    alarms.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.alarmsl)).setVisibility(View.VISIBLE);
	    		
	    	}
	    });
	    
	    ImageButton homeAlarm = (ImageButton) findViewById(R.id.homeAlarm);
	    homeAlarm.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.alarmsl)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    Button addAlarm = (Button) findViewById(R.id.addAlarm);
	    addAlarm.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		ImageButton alarmStatus = (ImageButton) findViewById(R.id.bellSmall);
	    		if (alarmSet == false) {
	    			showDialog(ALARM_DIALOG_ID);
	    			updateDisplay();
	    			alarmStatus.setVisibility(View.VISIBLE);
	    		}
	    	}
	    });
	    
	    ToggleButton alarmButton = (ToggleButton) findViewById(R.id.alarm01);
	    alarmButton.setVisibility(View.GONE);
	    alarmButton.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		ImageButton alarmStatus = (ImageButton) findViewById(R.id.bellSmall);
		    		if (alarm) {
		    			alarmStatus.setVisibility(View.GONE);
		    			alarm = false;
		    		} else {
		    			alarmStatus.setVisibility(View.VISIBLE);
		    			alarm = true;
		    		}
	    		}
	    });
	    alarmButton.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				showDialog(ALARM_DIALOG_ID);
    			updateDisplay();
				return false;
			}
	    });
	    
	    final Calendar c = Calendar.getInstance();
	    mHour = c.get(Calendar.HOUR_OF_DAY);
	    mMinute = c.get(Calendar.MINUTE);
	    
	    /* GPS Stuff */
	    ImageButton gps = (ImageButton) findViewById(R.id.gps);
	    gps.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.gpsl)).setVisibility(View.VISIBLE);
	    		WebView gpsView = (WebView) findViewById(R.id.webView1);
	    		gpsView.loadUrl("file:///android_res/drawable/map.png");
	    	}
	    });
	    
	    ImageButton homeGps = (ImageButton) findViewById(R.id.homeGps);
	    homeGps.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.gpsl)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    /*Settings Stuff */
	    ImageButton settings = (ImageButton) findViewById(R.id.settings);
	    settings.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.settingsl)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    ImageButton homeSettings = (ImageButton) findViewById(R.id.homeSettings);
	    homeSettings.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.settingsl)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    Button adjustTime = (Button) findViewById(R.id.editTime);
	    adjustTime.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		if (!timeSet) {
	    			Calendar cal = Calendar.getInstance();
	    			offHours = cal.get(Calendar.HOUR_OF_DAY);
                	offMin = cal.get(Calendar.MINUTE);
	    		}
	    		showDialog(TIME_DIALOG_ID);
	    	}
	    });
	    
	    Button adjustDate = (Button) findViewById(R.id.editDate);
	    adjustDate.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		//Datepicker doesnt like null values, so default them before opening it
    			Calendar cal = Calendar.getInstance();
    			offDay = cal.get(Calendar.DATE);
            	offMonth = cal.get(Calendar.MONTH) + 1;
            	offYear = cal.get(Calendar.YEAR);
	    		showDialog(DATE_DIALOG_ID);
	    	}
	    });
	    
	    ToggleButton ToggleDST = (ToggleButton) findViewById(R.id.editDST);
	    ToggleDST.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		if (DST == 0)
	    			DST = 1;
	    		else
	    			DST = 0;
	    	}
	    });
	    
	    /* Stopwatch Stuff */
	    ImageButton stopwatch = (ImageButton) findViewById(R.id.stopwatch);
	    stopwatch.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.stopwatchl)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    ImageButton homeStopwatch = (ImageButton) findViewById(R.id.homeStopwatch);
	    homeStopwatch.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.stopwatchl)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    ToggleButton startToggle = (ToggleButton) findViewById(R.id.start);
	    startToggle.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		if (!counting)
	    			counting = true;
	    		else
	    			counting = false;
	    	}
	    });
	    
	    Button clear = (Button) findViewById(R.id.clear);
	    clear.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		wHours = 0;
	    		wMin = 0;
	    		wSec = 0;
	    		TextView watch = (TextView) findViewById(R.id.watchText);
	    		watch.setText("00.00.00");
	    	}
	    });
	    
	    /* TimeZones Stuff */
	    ImageButton timezone = (ImageButton) findViewById(R.id.timezones);
	    timezone.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.timezonesl)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    ImageButton homeTimezones = (ImageButton) findViewById(R.id.homeTimezones);
	    homeTimezones.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		((LinearLayout) findViewById(R.id.timezonesl)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.main)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    Button addTimezone = (Button) findViewById(R.id.addTimezone);
	    addTimezone.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
    			showDialog(TIMEZONE_DIALOG_ID);
    			timezoneSet = true;
	    	}
	    });
	    
	    Button timezoneButton = (Button) findViewById(R.id.timezone01);
	    timezoneButton.setVisibility(View.GONE);
	    timezoneButton.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
    			showDialog(TIMEZONE_DIALOG_ID);
	    	}
	    });
	    
	    /* Alarm Ringing Stuff */
	    Button dismiss = (Button) findViewById(R.id.dismiss);
	    dismiss.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		alarm = false;
	    		ImageButton alarmStatus = (ImageButton) findViewById(R.id.bellSmall);
	    		alarmStatus.setVisibility(View.GONE);
	    		ToggleButton alarmButton = (ToggleButton) findViewById(R.id.alarm01);
	    		alarmButton.setChecked(false);
	    		((LinearLayout) findViewById(R.id.alarmRing)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.watch)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    Button snooze = (Button) findViewById(R.id.snooze);
	    snooze.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		int min = mMinute;
	    		min = min+5;
	    		if (min > 60)
	    			mHour+=1%(amPm ? 12 : 24);
	    		else
	    			min = min%60;
	    		mMinute = min;
	    		((LinearLayout) findViewById(R.id.alarmRing)).setVisibility(View.GONE);
	    		((LinearLayout) findViewById(R.id.watch)).setVisibility(View.VISIBLE);
	    	}
	    });
	    
	    //Nice little icon for our sliding drawer
	    final SlidingDrawer drawer = (SlidingDrawer) findViewById(R.id.slidingDrawer1);
	    final Button handle = (Button) findViewById(R.id.handle);
	    drawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
	    	public void onDrawerOpened() {
            		handle.setText("▼");
            		drawer.setBackgroundColor(Color.BLACK);
			}

	    });
	    drawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			public void onDrawerClosed() {
            		handle.setText("▲");
			}
		});
	    drawer.setOnDrawerScrollListener(new OnDrawerScrollListener() {

			public void onScrollEnded() {
				// TODO Auto-generated method stub
				
			}

			public void onScrollStarted() {
        		drawer.setBackgroundColor(Color.TRANSPARENT);
			}
	    });
	    
	    //Thread that runs our clock+stopwatch
	    Thread myThread = null;
	    Runnable runnable = new CountDownRunner(); 
	    myThread= new Thread(runnable);
	    myThread.start();
	 
	}
	
    //This does watch stuff
	public void doWork() { 
	    runOnUiThread(new Runnable() { 
	        public void run() { 
	            try{ 
	                TextView txtCurrentTime = (TextView)findViewById(R.id.clockText);
	                    Calendar cal = Calendar.getInstance();
	                    int hours = 0;
	                    if (amPm)
	                    	hours = (cal.get(Calendar.HOUR)+DST)%12;
	                    else
	                    	hours = (cal.get(Calendar.HOUR_OF_DAY)+DST);
	                    int minutes = cal.get(Calendar.MINUTE);
	                    int seconds = cal.get(Calendar.SECOND);
	                    if (timeSet) {
	                    	hours=offHours;
	                    	minutes=offMin;
	                    	if(seconds==59){
	                    		offMin++;
	                    	}
	                    	if(minutes==59){
	                    		offMin=0;
	                    		offHours++;
	                    	}
	                    }
	                    int am = cal.get(Calendar.AM_PM);
	                    String h2, m2, s2, a2 = null;
	                    h2 = formatString(hours);
	                    m2 = formatString(minutes);
						s2 = formatString(seconds);
						if (amPm) {
			                txtCurrentTime.setTextSize(50); //TODO: This size if different from the XML size, check this
							if (am == 0)
								a2 = " AM";
							else if (am == 1)
								a2 = " PM";
						}
						else 
							a2 = "";
	                    String curTime = h2 + ":" + m2 + a2; 
	                    txtCurrentTime.setText(curTime);
	                    if (timezoneSet) {
		                    Button timezoneButton = (Button) findViewById(R.id.timezone01);
		                    String h3 = formatString(hours + selTimezone);
		                    String curTime2 = h3 + ":" + m2 + a2; 
		                    timezoneButton.setText(curTime2);
		                    timezoneButton.setVisibility(0);
	                    }
	                TextView alarmClockText = (TextView)findViewById(R.id.clockTextAlarm);
	                alarmClockText.setText(curTime);
	                if (alarm && hours == mHour && minutes == mMinute) {
	                	((LinearLayout) findViewById(R.id.watch)).setVisibility(View.GONE);
	    	    		((LinearLayout) findViewById(R.id.alarmRing)).setVisibility(View.VISIBLE);
	                }
	                TextView txtCurrentDate = (TextView)findViewById(R.id.dateText);
	                	int day = cal.get(Calendar.DATE);
	                	int month = cal.get(Calendar.MONTH) + 1; // +1 because months start at 0 for some reason
	                	int year = cal.get(Calendar.YEAR);
	                	
	                	//I really cbfd writing logic for this to correct itself lol
	                	if (dateSet) {
	                		day=offDay;
	                		month=offMonth;
	                		year=offYear;
	                	}
	                	String curDate = day + " - " + month + " - " + year;
	                	txtCurrentDate.setText(curDate);
	                	
	                TextView watch = (TextView) findViewById(R.id.watchText);	
		                if (counting) {
		                	if (wSec == 59) {
		                		wSec = 0;
		                		wMin++;
		                	}
		                	if (wMin == 59) {
		                		wMin = 0;
		                		wHours++;
		                	}
		                	else
		                		wSec++;
		                	String w1, w2, w3 = null;
		                	w1 = formatString(wHours);
		                	w2 = formatString(wMin);
		                	w3 = formatString(wSec);
		                	String sWatch = w1 + "." + w2 + "." + w3;
		                	watch.setText(sWatch);
		                }
	            }catch (Exception e) {} 
	        } 
	    }); 
	} 
	 
	//Because I seem to be writing this too much - formats ints like 1 into a string of 01 else returns string value of int
	public String formatString(int i) {
		String s;
		if (i < 10)
			s = String.format("%02d", i);
		else
			s = Integer.toString(i);
		return s;
	}
	
    public void updateDisplay() {
    	ToggleButton alarmButton = (ToggleButton) findViewById(R.id.alarm01);
    	alarmButton.setTextOn(formatString(mHour) + ":" + formatString(mMinute));
    	alarmButton.setTextOff(formatString(mHour) + ":" + formatString(mMinute));
    	alarmSet=true;
    	alarmButton.setVisibility(0);
    	alarmButton.setChecked(true);
	}
     
    private TimePickerDialog.OnTimeSetListener mAlarmSetListener =
    	    new TimePickerDialog.OnTimeSetListener() {
    	        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    	            mHour = hourOfDay;
    	            mMinute = minute;
    	    		alarm = true;
    	            updateDisplay();
    	        }
    	    };
    
	private TimePickerDialog.OnTimeSetListener mTimeSetListener2 =
			 new TimePickerDialog.OnTimeSetListener() {
	    	 	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
	    	 		offHours = hourOfDay;
	    	 		offMin = minute;
	            	timeSet=true;
	    	    }
	    	};
	    	
	private DatePickerDialog.OnDateSetListener mDateSetListener =
			new DatePickerDialog.OnDateSetListener() {
				public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
	                        offYear = year;
	                        offMonth = monthOfYear;
	                        offDay = dayOfMonth;
	                    }
	                };
    	    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case ALARM_DIALOG_ID:
            return new TimePickerDialog(this, mAlarmSetListener, mHour, mMinute, false);
            
        case TIME_DIALOG_ID:
        	return new TimePickerDialog(this, mTimeSetListener2, offHours, offMin, false);
        case DATE_DIALOG_ID:
        	return new DatePickerDialog(this, mDateSetListener, offYear, offMonth, offDay);
        case TIMEZONE_DIALOG_ID:
        	final CharSequence[] items = {"-12", "-11", "-10", "-9", "-8", "-7", "-6", "-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"};

        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setTitle("Pick a timzone (from GMT)");
        	builder.setItems(items, new DialogInterface.OnClickListener() {
        	    public void onClick(DialogInterface dialog, int item) {
        	        selTimezone = Integer.parseInt(items[item].toString());
        	    }
        	});
        	AlertDialog alert = builder.create();
        	return alert;
        }
        return null;
    }
    
	class CountDownRunner implements Runnable{ 
	    // @Override 
	    public void run() { 
	            while(!Thread.currentThread().isInterrupted()){ 
	                try { 
	                doWork(); 
	                    Thread.sleep(1000); 
	                } catch (InterruptedException e) { 
	                        Thread.currentThread().interrupt(); 
	                }catch(Exception e){ 
	                } 
	            } 
	    } 
	}
	

}